package com.wu.deletenode;

/**
 * 删除链表中的节点（O(1)时间复杂度内完成）
 *
 * @author lynn
 * @date 2020/7/27 - 22:37
 */
class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Soution {

    public static void deleteNode(ListNode root, ListNode target) {
        if (root == null || target == null) {
            return;
        }
        if (target.next != null) {
            ListNode next = target.next;
            target.val = next.val;
            target.next = next.next;
        } else if (root == target) {
            root = null;
            target = null;
        } else {
            ListNode cur = root;
            while (cur.next != null) {
                if (cur.next == target) {
                    cur.next = target.next;
                    return;
                }
                cur = cur.next;
            }
        }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        deleteNode(node1, node5);
        while (node1 != null) {
            System.out.println(node1.val);
            node1 = node1.next;
        }
    }
}
